<?php
/**
 * Author: DefinitlyEvil
 * Created at: 2020/4/14 10:20
 */

namespace App\Tools;


class ECSTools
{

    private static $clientInitialized = false;

    public static function initClient() {
        if(self::$clientInitialized) return;
        \AlibabaCloud\Client\AlibabaCloud::accessKeyClient(
            getenv('AccessKeyID'),
            getenv('AccessKeySecret')
        )->regionId('cn-shenzhen')->asDefaultClient();
        self::$clientInitialized = true;
    }

    const EXPIRE_TIME = 50 * 60;

    public static function createEcs($gamemode = GameModes::EXPLOSIVE, $map = "xngc")
    {
        $userData = file_get_contents('../cloudinit.yml');
        $userData = str_replace('%AKID%', getenv('AccessKeyID'), $userData);
        $userData = str_replace('%AKS%', getenv('AccessKeySecret'), $userData);
        $userData = str_replace('%GAMEMODE%', $gamemode, $userData);
        $userData = str_replace('%MAP%', $map, $userData);

        date_default_timezone_set('GMT');

        $exp_time = date('Y-m-d\\TH:i:s\\Z', time() + self::EXPIRE_TIME);

        $options = [
            "RegionId" => "cn-shenzhen",
            "ZoneId" => "cn-shenzhen-b",
            "InstanceType" => getenv('ECS_TYPE'),
            "withInstanceChargeType" => "PostPaid",
            "SpotStrategy" => "SpotAsPriceGo",

            "ResourceGroupId" => getenv("ECS_RESOURCE_GROUP_ID"),

            "KeyPairName" => getenv("ECS_KEY_PAIR_NAME"),

            "UniqueSuffix" => true,
            "InstanceName" => getenv('ECS_INSTANCE_NAME'),
            "HostName" => getenv('ECS_HOSTNAME'),

            "InternetChargeType" => "PayByTraffic",
            "InternetMaxBandwidthIn" => 100,
            "InternetMaxBandwidthOut" => 1,

            "VSwitchId" => getenv("ECS_VSWITCH_ID"),
            "SecurityGroupId" => getenv("ECS_SECURITY_GROUP_ID"),

            "SystemDisk.Size" => 20,
            "ImageId" => "debian_10_3_x64_20G_alibase_20200329.vhd",

            "UserData" => base64_encode($userData),

            "AutoReleaseTime" => $exp_time,

            "Tag.1.Key" => "type",
            "Tag.1.Value" => "MCFireServer",
            "Tag.2.Key" => "room",
            "Tag.2.Value" => "1",

            "Amount" => 1,
            "MinAmount" => 1,

            // "DryRun" => true,
        ];

        self::initClient();

        $create = \AlibabaCloud\Ecs\Ecs::v20140526()->runInstances(['query' => $options])
            // ->debug(true)
            ->timeout(5)
            ->request()->toArray();

        $instance_id = $create['InstanceIdSets']['InstanceIdSet'][0];

        return $instance_id;
    }

    public static function getInstancePublicIP($instanceId) {
        $options = ['InstanceId' => $instanceId];
        $response = \AlibabaCloud\Ecs\Ecs::v20140526()->describeInstanceAttribute(['query' => $options])
            // ->debug(true)
            ->timeout(5)
            ->request()->toArray();

        $public_ip = $response['PublicIpAddress']['IpAddress'][0];
        return $public_ip;
    }

    public static function delete($instanceId) {
        $options = ['InstanceId' => $instanceId, 'Force' => true];
        $response = \AlibabaCloud\Ecs\Ecs::v20140526()->deleteInstance(['query' => $options])
            ->timeout(5)
            ->request()->toArray();

        return $response;
    }
}